<template>
  <div class="wrap" v-if="dataReady">
    <div class="head">
      <div class="current">
        <div>当前关卡</div>
        <div class="c-num">{{dayCount}}</div>
      </div>
      <div class="time">
        <timeCount :initBtn="initTimeCount" :startBtn="startTimeCount" initTime="10" :stopBtn="stopTimeCount" @timeout="timeoutHandle"></timeCount>
      </div>
      <div class="record">
        <div>最高纪录</div>
        <div class="r-num">{{topCount}}</div>
      </div>
      <div class="title-type" :class="{titleTypeIn:showTitleType}" @animationend="animationStep1">{{questionType}}<img src="/static/titleType.png" alt=""></div>
      <div class="title-number" :class="{titleNumberIn:showTitleType}">第{{dayCount}}题</div>
    </div>
    <div class="content">
      <div class="title" @transitionend="animationStep2" :class="{titleIn:showTitle}">{{subjecList.title}}</div>
      <div class="select-list" :class="{listIn:showAnsList}">
        <div class="select-item" :class="{success:item.state=='success',fail:item.state=='fail',noSelect:item.noSelect}" v-for="(item,index) in selectList" :key="index" @click="select(item,index)">
          <img v-if="item.state=='success'" class="left-img" src="/static/sIcon.png" alt="">
          <img v-if="item.state=='fail'" class="left-img" src="/static/fIcon.png" alt=""> {{item.name}}
        </div>
      </div>
    </div>
    <!-- 结果弹窗 -->
    <div class="result-box" v-if="showResult">
      <div class="cvs">
        <img class="result-img" v-if="resultImg" :src="resultImg" alt="">
        <canvas canvas-id="myCanvas"></canvas>
      </div>
      <div class="save-btn" @click="saveImg">炫耀一下</div>
      <div class="back-btn" @click="back">点击跳过</div>
    </div>
  </div>
</template>

<script>
import { mapState, mapMutations } from "vuex";
import timeCount from "@/pages/game/components/timeCount";
let dataStack = [];
export default {
  components: {
    timeCount
  },
  data() {
    return {
      dataReady: false,
      initTimeCount: false,
      startTimeCount: false,
      stopTimeCount: false,
      subjecList: [],
      selectList: [],
      dayCount: 0,
      topCount: 0,
      hasAnswer: false,
      // 动画相关
      animationTime: 1,
      showTitleType: false,
      showTitle: false,
      showAnsList: false,
      audio: {},
      resultImg: null,
      showResult: false,
      headImgPath: ""
    };
  },
  computed: {
    ...mapState(["deviceInfo", "appInfo"]),
    questionType() {
      if (this.subjecList) {
        let type = this.subjecList.parentType;
        let obj = {
          1: "德",
          2: "商",
          3: "文",
          4: "理",
          5: "艺",
          6: "体"
        };
        return obj[type];
      }
    }
  },
  methods: {
    ...mapMutations(["setDayCount", "setIsDayChallenge"]),
    getData() {
      return new Promise((resolve, reject) => {
        this.fly.post("dayChallenge/getSubject").then(res => {
          this.setDayCount(res.data.Result.dayCardNumber - 1);
          this.dayCount = res.data.Result.dayCardNumber;
          this.topCount = res.data.Result.weekMaxCardNumber;
          this.subjecList = res.data.Result.subject[0];
          this.selectList = res.data.Result.subject[0].optionList;
          this.dataReady = true;
          this.hasAnswer = false;
          resolve();
        });
      });
    },
    select(item, index) {
      //答题
      if (!this.hasAnswer) {
        if (item.sortId == this.subjecList.optionSortId) {
          //回答正确
          item.state = "success";
          this.audioPlay("success");
          this.hasAnswer = true;
          this.stopTimeCount = !this.stopTimeCount;

          for (let i = 0; i < this.selectList.length; i++) {
            if (index != i) {
              this.selectList[i].noSelect = true;
            }
          }
          // TODO 提交答案
          this.fly
            .post("dayChallenge/submitSubject", {
              subjectId: this.subjecList.id,
              answer: item.sortId
            })
            .then(res => {
              setTimeout(() => {
                this.showTitle = false;
                this.showAnsList = false;
                this.initTimeCount = !this.initTimeCount;
                // 提交答案
                setTimeout(() => {
                  this.getData().then(() => {
                    this.showTitleTag();
                  });
                }, 1000);
              }, 1000);
            });
        } else {
          item.state = "fail";
          this.audioPlay("fail");
          this.hasAnswer = true;
          this.stopTimeCount = !this.stopTimeCount;
          // 隐藏选项
          for (let i = 0; i < this.selectList.length; i++) {
            if (this.selectList[i].sortId == this.subjecList.optionSortId) {
              this.selectList[i].state = "success";
            } else if (
              this.selectList[i].sortId != this.subjecList.optionSortId &&
              index != i
            ) {
              this.selectList[i].noSelect = true;
            }
          }
          // 失败 就退出TODO  结果页
          this.showResult = true;
          this.getResult();
          // this.setIsDayChallenge(1);
        }
      }
    },
    back() {
      this.$router.back();
      this.showResult = false;
    },
    getResult() {
      //获取挑战结果
      wx.showLoading({
        title: "绘制中",
        mask: false
      });
      let ctx = wx.createCanvasContext("myCanvas");
      let w = this.deviceInfo.width * 0.73,
        h = 1.6 * w;
      let promise1 = new Promise(function(resolve, reject) {
        wx.getImageInfo({
          src: "../../static/poster/qr.jpg",
          success: function(res) {
            console.log(res);
            resolve(res);
          }
        });
      });
      let promise2 = new Promise((resolve, reject) => {
        /* 获得要在画布上绘制的图片 */
        wx.getImageInfo({
          src: "../../static/dayPoster.jpg",
          success: function(res) {
            console.log(res);
            resolve(res);
          }
        });
      });
      let promise3 = new Promise((resolve, reject) => {
        /* 获得要在画布上绘制的图片 */
        wx.getImageInfo({
          src: this.appInfo.headImgUrl,
          success: function(res) {
            console.log(res);
            resolve(res);
          }
        });
      });
      Promise.all([promise1, promise2,promise3]).then(res => {
        ctx.drawImage("/" + res[1].path, 0, 0, w, h);
        ctx.drawImage(
          "/" + res[0].path,
          0.767 * w,
          0.84 * h,
          0.18 * w,
          0.135 * h
        );
        //用户头像
        ctx.save();
        ctx.beginPath();
        ctx.arc(w / 2, 0.14 * h, 0.135 * w, 0, 2 * Math.PI);
        ctx.clip();
        ctx.drawImage(
          res[2].path,
          w / 2 - 0.135 * w,
          0.14 * h - 0.135 * w,
          0.27 * w,
          0.27 * w
        );
        ctx.closePath();
        ctx.restore();
        // //用户昵称
        // this.setFontStyle(ctx, "#9a9a9a", 12, "center", w);
        ctx.setFillStyle("#000");
        ctx.setFontSize(14);
        ctx.setTextAlign("center");
        ctx.fillText(this.appInfo.nickname, w / 2, 0.275 * h);
        ctx.restore();
        ctx.font = "bold";
        ctx.setFillStyle("#fff");
        ctx.setFontSize(38);
        ctx.setTextAlign("center");
        ctx.fillText(this.dayCount - 1, w / 2, 0.77 * h);
        ctx.draw(false, () => {
          wx.canvasToTempFilePath({
            x: 0,
            y: 0,
            fileType: "png",
            quality: 1,
            canvasId: "myCanvas",
            success: res => {
              this.resultImg = res.tempFilePath;
              wx.hideLoading();
            }
          });
        });
      });
    },

    timeoutHandle() {
      // 失败 就退出TODO
      this.hasAnswer = true;
      this.showResult = true;
      this.getResult();
    },
    showTitleTag() {
      this.showTitleType = true;
      setTimeout(() => {
        this.showTitleType = false;
      }, 1500);
    },
    animationStep1() {
      setTimeout(() => {
        this.showTitle = true;
      }, 100);
    },
    animationStep2() {
      if (this.animationTime % 2 != 0) {
        this.showAnsList = true;
        this.startTimeCount = !this.startTimeCount;
      }
      this.animationTime++;
    },
    initAudio() {
      this.audio = wx.createInnerAudioContext();
    },
    audioPlay(type) {
      if (type == "success") {
        this.audio.src = "/static/audio/right.mp3";
      } else {
        this.audio.src = "/static/audio/wrong.mp3";
      }
      this.audio.play();
    },
    saveImg() {
      wx.saveImageToPhotosAlbum({
        filePath: this.resultImg,
        success: res => {
          console.log(res);
          console.log(this.resultImg);
        },
        fail: res => {
          // 拒绝过授权重新 调用授权
          console.log(res);
          wx.getSetting({
            success(res) {
              console.log(res);
              if (!res.authSetting["scope.writePhotosAlbum"]) {
                wx.showToast({ title: "需要获取保存相册功能", icon: "none" });
              }
            }
          });
        }
      });
    }
  },
  mounted() {
    this.getData();
    this.initAudio();
    setTimeout(() => {
      this.showTitleTag();
    }, 1000);
    setTimeout(() => {
      if (!this.showTitle) {
        this.showTitle = true;
      }
    }, 2800);
  },
  onLoad(options) {
    dataStack.push({ ...this.$data });
  },
  onUnload() {
    this.fly.post("dayChallenge/submitSubject", {
      subjectId: this.subjecList.id,
      answer: -1
    });
    Object.assign(this.$data, dataStack.pop());
    this.hasAnswer = false;
    this.showTitle = false;
  },
  onShow() {}
};
</script>

<style lang="scss" scoped>
.wrap {
  width: 100%;
  height: 100%;
  background-size: 750rpx 714rpx;
  background-position: bottom;
  background-repeat: no-repeat;
  background-image: url("");
}
.head {
  display: flex;
  justify-content: center;
  align-items: flex-start;
  padding-top: 80rpx;
  box-sizing: border-box;
  .time {
    padding: 0 94rpx;
  }
  .current,
  .record {
    display: flex;
    flex-direction: column;
    font-size: 24rpx;
    margin-top: 6rpx;
    & > div {
      line-height: 1;
      text-align: center;
    }
  }
  .current {
    .c-num {
      font-size: 50rpx;
      font-weight: bold;
      color: #67c29f;
      margin-top: 20rpx;
    }
  }
  .record {
    .r-num {
      font-size: 50rpx;
      font-weight: bold;
      color: #f5af4b;
      margin-top: 20rpx;
    }
  }
}

.title {
  height: 206rpx;
  display: flex;
  justify-content: center;
  align-items: center;
  text-align: center;
  font-size: 42rpx;
  padding: 0 50rpx;
  box-sizing: border-box;
  opacity: 0;
  transition: all 0.8s ease;
}

.titleIn {
  opacity: 1;
}
.select-list {
  height: 590rpx;
  display: flex;
  flex-direction: column;
  justify-content: space-around;
  align-items: center;
  margin-bottom: 40rpx;
  .select-item {
    width: 542rpx;
    height: 120rpx;
    position: relative;
    font-size: 40rpx;
    border: 3rpx solid #ababab;
    border-radius: 10rpx;
    box-sizing: border-box;
    transition: all 0.4s ease;
    opacity: 0;
    transform: scale(0);
    // filter: drop-shadow(0 0 6px rgba(0, 0, 0, 0.4));
    box-shadow: 0 0 20rpx 6rpx rgba(0, 0, 0, 0.25);
    display: flex;
    justify-content: center;
    align-items: center;
    background-size: 536rpx 114rpx;
    background-repeat: repeat-y;
    background-image: url("");
    img {
      position: absolute;
      width: 28rpx;
      height: 28rpx;
      top: 50%;
      transform: translateY(-50%);
    }
    .left-img {
      left: 14rpx;
    }
    .right-img {
      right: 14rpx;
    }
  }

  .success,
  .fail {
    border: 6rpx solid #fff;
    color: #fff;
    animation: btnScale 0.4s ease;
  }
  .success {
    background: #67c29f;
  }
  .fail {
    background: #fd5c5c;
  }
  .noSelect {
    transform: scale(0) !important;
    opacity: 0 !important;
  }
}
.listIn {
  .select-item {
    transform: scale(1);
    opacity: 1;
  }
}
@keyframes btnScale {
  50% {
    transform: scale(1.2);
  }
  100% {
    transform: scale(1);
  }
}

.title-type,
.title-number {
  position: absolute;
  left: 50%;
  opacity: 0;
}
.title-type {
  transform: translate(-50%, 180rpx);
  font-size: 60rpx;
  color: #67c29f;
  text-align: center;
  img {
    position: absolute;
    width: 265rpx;
    height: 92rpx;
    bottom: -46rpx;
    left: 50%;
    transform: translateX(-50%);
  }
}
.title-number {
  transform: translate(-50%, 310rpx);
  font-size: 40rpx;
  color: #6b6a6b;
  text-align: center;
  font-size: 90rpx;
  font-weight: bold;
}
.titleTypeIn {
  animation: ttIn 1.28s ease;
}
.titleNumberIn {
  animation: tnIn 1.28s ease;
}

@keyframes ttIn {
  0% {
    transform: translate(-50%, 180rpx);
    opacity: 0;
  }
  33% {
    transform: translate(-50%, 200rpx);
    opacity: 1;
  }
  66% {
    transform: translate(-50%, 200rpx);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, 220rpx);
    opacity: 0;
  }
}

@keyframes tnIn {
  0% {
    transform: translate(-50%, 310rpx) scale(0);
    opacity: 1;
  }
  33% {
    transform: translate(-50%, 330rpx) scale(1);
    opacity: 1;
  }
  66% {
    transform: translate(-50%, 330rpx) scale(1);
    opacity: 1;
  }
  100% {
    transform: translate(-50%, 330rpx) scale(0);
    opacity: 0;
  }
}

.result-box {
  width: 100%;
  height: 100%;
  position: absolute;
  left: 0;
  top: 0;
  background: rgba(#000, 0.7);
  z-index: 999;
  padding-top: 50rpx;
  box-sizing: border-box;
  .cvs {
    width: 550rpx;
    height: 885rpx;
    margin: 0 auto;
    position: relative;
    .result-img {
      position: absolute;
      z-index: 100;
      width: 100%;
      height: 100%;
      left: 0;
      top: 0;
    }
  }
}
.save-btn {
  margin: 54rpx auto 20rpx auto;
  width: 330rpx;
  height: 94rpx;
  line-height: 94rpx;
  font-size: 40rpx;
  color: #fff;
  box-sizing: border-box;
  border: 2rpx solid #fff;
  border-radius: 8rpx;
  text-align: center;
}
.back-btn {
  font-size: 30rpx;
  color: #fff;
  text-align: center;
}

canvas {
  width: 552rpx;
  height: 885rpx;
}
</style>
